<?php

namespace App\Repositories;

use Carbon\Carbon;
use App\Enums\RewardEnum;
use App\Exceptions\BasicException;

class TreasureLogRepository
{
    public function getLastTreasureLog($user_id)
    {
        return app('model_treasure_log')->orderBy('id', 'desc')->where(['user_id' => $user_id])->first();
    }

    //获取可领取宝箱的剩余时间
    public function getLeftTime($user_id)
    {
        //宝箱倒计时
        $refresh_time = app('model_config')->getValue('TREASURE_BOX_REFRESH_TIME');
        $refresh_time = $refresh_time > 0 ? $refresh_time : 7200;
        $treasure_log = $this->getLastTreasureLog($user_id);
        if (!$treasure_log) {
            $time = 0;
        } else {
            $time = $refresh_time - (Carbon::now()->timestamp - $treasure_log->add_time);
            if ($time <= 0) {
                $time = 0;
            }
        }

        return $time;
    }

    public function formatLeftTime($left_time)
    {
        if ($left_time <= 0) {
            return '可领取';
        }
        if ($left_time >= 3600) {
            $hour        = floor($left_time / 3600);
            $minute      = floor(($left_time - $hour * 3600) / 60);
            $seconds     = $left_time - $hour * 3600 - $minute * 60;
            $time_format = str_pad($hour, 2, '0', STR_PAD_LEFT) . ':' . str_pad($minute, 2, '0',
                    STR_PAD_LEFT) . ':' . str_pad($seconds, 2, '0', STR_PAD_LEFT);
        } elseif ($left_time >= 60) {
            $minute      = floor($left_time / 60);
            $seconds     = $left_time - $minute * 60;
            $time_format = str_pad($minute, 2, '0', STR_PAD_LEFT) . ':' . str_pad($seconds, 2, '0', STR_PAD_LEFT);
        } else {
            $time_format = str_pad($left_time, 2, '0', STR_PAD_LEFT);
        }

        return $time_format;
    }

    public function openTreasureBox($user_id)
    {
        $left_time = $this->getLeftTime($user_id);
        if ($left_time > 0) {
            throw new BasicException(20110);
        }
        app('model_treasure_log')->insert(['user_id' => $user_id, 'add_time' => Carbon::now()->timestamp]);

        app('repo_reward')->setChannel(RewardEnum::REWARD_SOURCE_TYPE_BOX);
        app('repo_reward')->sendRewardItem($user_id, [21 => 10]);
    }
}
